# -*- coding: utf-8 -*-

import os
import logging


import pythoncom
from win32com import client

from py_win import py_dir_path


def word_export_pdf(word_path, pdf_path) -> bool:
    """
    将word导出pdf，注意必须使用绝对路径
    :param word_path:
    :param pdf_path:
    :return:
    """
    try:
        # 多线程初始化
        pythoncom.CoInitialize()
        # 启动word，打开文档
        # word = client.Dispatch("word.application")
        # word = client.DispatchEx("word.application")
        word = client.gencache.EnsureDispatch("word.application")
        document = word.Documents.Open(word_path, ReadOnly=1)

        # 如果pdf已存在就先删除再导出
        if os.path.exists(pdf_path):
            os.remove(pdf_path)
            pass

        # 另存为pdf：要求office>=2010
        document.SaveAs(pdf_path, FileFormat=17)
        # 关闭文档，退出word
        document.Close()
        word.Quit()
        # 释放资源
        pythoncom.CoUninitialize()
        return True
    except Exception as e:
        logging.exception(e)
        return False
    pass


if __name__ == '__main__':
    # 使用绝对路径
    word_path = os.path.join(py_dir_path, 'word.docx')
    pdf_path = os.path.join(py_dir_path, 'pdf.pdf')
    flag = word_export_pdf(word_path, pdf_path)

    pass
